module('lgx.codecell', package.seeall)
local decl   = require'lgx.decl'
local strbuf = require'lgx.strbuf'
mt = {}
mt.__index = function (tab, key)
    local val = rawget(tab, key) 
    if val then return val end

    val = rawget(mt, key)
    if val then return val end

    local declitem = rawget(tab, 'decl')
    if declitem then
        val = declitem[key]
        if val then return val end
    end
    return nil
end

------------------------------------------------------------------------
--  new codecell, codecell is just a wrapper of decl, with more code 
--  generation info.
------------------------------------------------------------------------
function new(o)
    assert(o.decl, 'argument "decl" must be given')
    assert(o.ids, 'argument "ids" must be given')
    assert(o.gen, 'argument "gen" must be given')
    o.before = nil  --code insert before this cell
    o.after  = nil  --code insert after this cell
    o.policy = nil  --policy for this cell
    o.basetab= {}
    setmetatable(o,mt)
    return o
end

------------------------------------------------------------------------
--  generate code of self
------------------------------------------------------------------------
function mt:gencode()
    assert(self.gen, 'codecell.gen is nil!')
    assert(self.gen[self.tag], string.format('codecell.gen.%s is nil', self.tag))
    return self.gen[self.tag](self)
end

function mt:__tostring()
    local s = strbuf.new()
    for k,v in pairs(self) do
        s = s + string.format('[%s]=%s', tostring(k), tostring(v))
    end
    return '{'..s:concat(',')..'}'
end
